<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .box {
      width: 150px;
      height: 150px;
      background-color: #6ff;
      position: absolute;
      left: 100px;
      top: 100px;
    }
  </style>
</head>

<body>
  <div class="box"></div>
</body>
<script>
  // 需求 拖拽盒子移动  松开时盒子停留在当前位置

  // onmousedown  先按下,记录按下的位置(移动需要)
  // onmousemove  再移动, 元素跟随鼠标移动 
  // onmouseup    再松开, 元素停留在当前位置

  var box = document.getElementsByClassName("box")[0];

  //  onmousedown  先按下,记录按下的位置(移动需要)
  box.onmousedown = function (e) {
    var e = e || window.event;

    // 计算获取
    var posX = e.pageX - box.offsetLeft;
    var posY = e.pageY - box.offsetTop;
    console.log(posX, posY);

    // 快捷获取
    var posX = e.offsetX;
    var posY = e.offsetY;
    console.log(posX, posY);

    // 先按下 再移动
    // onmousemove  再移动, 元素跟随鼠标移动 
    document.onmousemove = function (e) {
      var e = e || window.event;
      var x = e.pageX - posX;
      var y = e.pageY - posY;

      box.style.left = x + "px";
      box.style.top = y + "px";

    }

    // onmouseup 再松开, 元素停留在当前位置(移动事件不在生效)  
    document.onmouseup = function () {
      document.onmousemove = null;
    }


  }





</script>

</html>